#!/usr/bin/python3

import os
import subprocess as sub


def cpu():
    p = sub.Popen(['uptime'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    p.wait()
    m1, m5, m15 = stdout.replace(',', '').split()[-3:]
    return '1 minute: %s\n5 minutes: %s\n15 minutes: %s\n' % (m1, m5, m15)


def ram():
    p = sub.Popen(['free'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    total, used, free = stdout.splitlines()[1].split()[1:4]
    return 'total: %s\nused: %s\nfree: %s\n' % (total, used, free)


def hd():
    p = sub.Popen(['df', '-h'], stdout=sub.PIPE)
    stdout = p.stdout.read().decode()
    lines = stdout.splitlines()
    root_line = [line for line in lines if line.endswith('/')][0]
    dev, size, used, avail, pct = root_line.split()[:5]
    fmt = 'dev: %s\nsize: %s\nused: %s\navail: %s\npct: %s\n'
    return fmt % (dev, size, used, avail, pct)


if __name__ == '__main__':
    qs = os.getenv('QUERY_STRING')
    if 't=cpu' in qs:
        text = cpu()
    elif 't=ram' in qs:
        text = ram()
    elif 't=hd' in qs:
        text = hd()
    else:
        text1 = cpu()
        text2 = ram()
        text3 = hd()
        text = 'CPU:\n%s\nRAM:\n%s\nHD:\n%s' % (text1, text2, text3)
    print('Content-Type: text/plain\n\n', end='')
    print(text)
